package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.domain.UserLike;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //查询今日佳人
    @Override
    public RecommendUser selectBest(Long toUserId) {
        //根据toUserId查询，根据评分score排序，获取第一条
        //构建Criteria
        Criteria userId1 = Criteria.where("toUserId").is(toUserId);
        //构建query对象
        Query query =
                Query.query(userId1).with(Sort.by(Sort.Order.desc("score")))
                        .limit(1);
        //调用mongoTemplate查询
        return mongoTemplate.findOne(query, RecommendUser.class);
    }

    //推荐好友列表
    @Override
    public PageResult queryRecommendUserList(Integer page, Integer pagesize, Long toUserId) {
        //构建query对象
        Query query = new Query(Criteria.where("toUserId").is(toUserId));
        //总记录数
        long count = mongoTemplate.count(query, RecommendUser.class);
        query.skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("score")));
        //查询数据列表
        List<RecommendUser> recommendUsers =
                mongoTemplate.find(query, RecommendUser.class);
        //封装到 PageResult pageResult
        PageResult pageResult = new PageResult(page, pagesize, count, recommendUsers);
        return pageResult;
    }


    /**
     * 查询用户之间的推荐信息
     * bestid为推荐的id, userid为touserid
     */
    @Override
    public RecommendUser queryByUserId(Long bestId, Long userId) {
        Criteria criteria = Criteria.where("toUserId").is(userId)
                .and("userId").is(bestId);
        Query query = Query.query(criteria);
        RecommendUser user = mongoTemplate.findOne(query, RecommendUser.class);
        if (user == null) {
            user = new RecommendUser();
            user.setUserId(bestId);
            user.setToUserId(userId);
            user.setScore(95d);
        }
        return user;
    }

    /**
     * 1、排除喜欢，不喜欢的用户
     * 2、随机展示
     * 3、指定数量
     */
    @Override
    public List<RecommendUser> queryCardsList(Long userId, int count) {
        //1.查询喜欢和不喜欢的用户id
        List<UserLike> likeList =
                mongoTemplate.find(Query.query(Criteria.where("userId")
                        .is(userId)), UserLike.class);
        //获取喜欢的ids
        List<Long> likeUserIds =
                CollUtil.getFieldValues(likeList, "likeUserId", Long.class);
        //2构造查询推荐用户对象
        Criteria criteria =
                Criteria.where("toUserId").is(userId)
                        .and("userId").nin(likeUserIds);
        //3、使用统计函数，随机获取推荐的用户列表
        TypedAggregation<RecommendUser> newAggregation =
                TypedAggregation.newAggregation(RecommendUser.class,
                Aggregation.match(criteria), //指定查询条件
                Aggregation.sample(count));

        AggregationResults<RecommendUser> results =
                mongoTemplate.aggregate(newAggregation, RecommendUser.class);
        //4.构造返回
        return results.getMappedResults();
    }
}
